<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input
          v-model="queryParams.noticeTitle"
          placeholder="请输入公告标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['system:notice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:notice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:notice:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div ref="divTable" :style="'height:' + divHeight + 'px'">
      <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="50">
          <template v-slot="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="公告标题" align="center" prop="noticeTitle" :show-overflow-tooltip="true" />
        <el-table-column label="有效期" align="center" prop="validTime" >
          <template v-slot="scope">
            {{ $parseTime(scope.row.validFrom, '{y}-{m}-{d}') }} ~ {{ $parseTime(scope.row.validTo, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
        <el-table-column label="公告版本" align="center" prop="noticeVersion" width="100">
          <template v-slot="scope">
            <el-tag type="success">{{ scope.row.noticeVersion }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_notice_status" :value="scope.row.noticeStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="创建者" align="center" prop="createBy" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="100">
          <template slot-scope="scope">
            <span>{{ $parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              :icon="scope.row.noticeStatus === 'UNPUBLISHED' ? 'el-icon-position' : 'el-icon-close'"
              @click="handleChangeStatus(scope.row)"
              v-hasPermi="['system.notice:changeStatus']"
            >{{scope.row.noticeStatus === 'UNPUBLISHED' ? "发布" : "撤销" }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handlePreView(scope.row)"
              v-hasPermi="['system.notice:preView']"
            >预览</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:notice:edit']"
              v-if="scope.row.noticeStatus === 'UNPUBLISHED'"
            >修改</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :pageRefs="this.$refs"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="公告标题" prop="noticeTitle">
              <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公告版本" prop="noticeVersion">
              <el-input v-model="form.noticeVersion" placeholder="请输入公告版本" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有效期" prop="validTime">
              <el-date-picker style="width: 100%"
                v-model="form.validTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="noticeContent">
              <editor v-model="form.noticeContent" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--通知公告预览 -->
    <el-dialog :visible.sync="preViewOpen" :title="preTitle" width="800px" append-to-body>
      <div v-loading="loading" class="content">
        <div v-html="form.noticeContent" style="margin-left:10px;margin-right:10px" class="ql-editor"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="preViewClose">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listNotice, getNotice, delNotice, addNotice, updateNotice, updateChangeStatus, isExistPublishedNotice } from "@/api/system/notice";
import ResizeMixin from "@/layout/mixin/ResizeHandler";

export default {
  name: "Notice",
  mixins: [ResizeMixin],
  dicts: ['sys_notice_status'],
  data() {
    return {
      // div高度
      divHeight: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告表格数据
      noticeList: [],
      // 弹出层标题
      title: "",
      // 公告预览弹出层标题
      preTitle: "",
      // 是否显示弹出层
      open: false,
      // 是否显示公告预览弹出层
      preViewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeTitle: undefined,
        createBy: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        noticeTitle: [
          { required: true, message: "公告标题不能为空", trigger: "blur" }
        ],
        noticeVersion: [
          { required: true, message: "公告版本不能为空", trigger: "blur" },
          {
            pattern: /^V\d+(\.\d+){2}$/, // 正则表达式校验格式
            message: "公告版本格式必须为 V1.0.0 这种格式",
            trigger: "blur"
          }
        ],
        validTime: [
          { required: true, message: "有效期不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (!this.form.validTime || this.form.validTime.length === 0) {
                callback(new Error("有效期不能为空"));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ],
      },
      // 有效期范围
      dateRange: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询公告列表 */
    getList() {
      this.loading = true;
      listNotice(this.queryParams).then(response => {
        this.noticeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        noticeTitle: null,
        noticeContent: null,
        noticeStatus: null,
        noticeVersion: null,
        validTime: [],
      };
      this.$resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getNotice(id).then(response => {
        this.form = {
          ...response.data,
          validTime: [response.data.validFrom, response.data.validTo],
        }
        this.open = true;
        this.title = "修改公告";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form = {
            ...this.form,
            validFrom: this.form.validTime[0],
            validTo: this.form.validTime[1],
          }
          if (this.form.id !== null) {
            updateNotice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNotice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除公告编号为"' + ids + '"的数据项？').then(function() {
        return delNotice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 预览功能*/
    handlePreView(row){
      getNotice(row.id).then(response => {
        this.preTitle = response.data.noticeTitle;
        this.form = response.data;
        this.preViewOpen = true;
      });
    },
    /** 关闭预览页面*/
    preViewClose(){
      this.preViewOpen = false;
    },
    /** 发布和撤销 */
    handleChangeStatus(row){
      const ids = row.id || this.ids;
      let status = row.noticeStatus === 'PUBLISHED' ? '撤销' : '发布';

      this.$modal.confirm(`是否确认${status}此公告内容？`).then(async () => {
        const res = await isExistPublishedNotice(ids);
        if (res.data) {
          throw new Error();
        }
        row.noticeStatus = row.noticeStatus === 'PUBLISHED' ? 'UNPUBLISHED' : 'PUBLISHED';
        return updateChangeStatus({ ids: ids, status: row.noticeStatus });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(`${status}成功`);
      }).catch((action) => {
        if (action !== 'cancel' && action !== 'close') {
          this.$modal.msgWarning("当前已存在发布的公告，请先撤销已发布的公告！");
        }
      });
    }
  }
};
</script>

<style scoped>
/deep/ .ql-editor img {
  max-width: 50%;
  height: 50%;
}
/deep/ .ql-editor {
  overflow: auto;
}
</style>
